package com.ccdt.tv.smartrecommend.view.web;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JavascriptInterface;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.ccdt.tv.smartrecommend.Constant;
import com.ccdt.tv.smartrecommend.FromLiveBean;
import com.ccdt.tv.smartrecommend.model.bean.RecordBean;
import com.ccdt.tv.smartrecommend.utils.DVBServiceManager;
import com.ccdt.tv.smartrecommend.utils.FileUtil;
import com.ccdt.tv.smartrecommend.utils.GetTokenServiceHelper;
import com.ccdt.tv.smartrecommend.utils.JsonUtil;
import com.ccdt.tv.smartrecommend.utils.RecordDBUtil;
import com.ccdt.tv.smartrecommend.utils.SystemPropUtil;
import com.ccdt.tv.smartrecommend.view.bean.IntentEventBean;
import com.ccdt.tv.smartrecommend.view.tools.OutEventBus;
import com.ccdt.tv.smartrecommend.view.widget.layout.FloatLayout;
import com.google.gson.Gson;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class SRJsInterface {
    private final String TAG = this.getClass().getSimpleName();
    private static FloatLayout mView;
    private final GetTokenServiceHelper mTokenHelper;
    private final DVBServiceManager mDVBServiceManager;
    private final RecordDBUtil mRecordDBUtil;
    private Gson mGson;

    public SRJsInterface(FloatLayout view) {
        this.mView = view;
        mTokenHelper = GetTokenServiceHelper.getInstance();
        //绑定DVB服务
        mDVBServiceManager = DVBServiceManager.getInstance(Utils.getApp());
//        mDVBServiceManager.bindService();
        mRecordDBUtil = RecordDBUtil.getInstance(Utils.getApp());
        mGson = new Gson();
    }

    //在js中调用window.android.openMoviePlayer(name)便会触发此方法,调用Launcher播放器播放
    @JavascriptInterface
    public void openMoviePlayer(String name) {
        Log.w(TAG, "openMoviePlayer name = " + name);
    }

    //获取机顶盒卡号区域码等信息
    @JavascriptInterface
    public String getCaInfo() {
        if (mTokenHelper.isAuth().equals("0000")) {
            return mTokenHelper.getUserInfo();
        } else {
            ToastUtils.showShort(mTokenHelper.isAuth());
            return "";
        }
    }

    //获取机顶盒订购的产品
    @JavascriptInterface
    public String getBoxProducts() {
        if (mTokenHelper.isAuth().equals("0000")) {
            return mTokenHelper.getProducts();
        } else {
            ToastUtils.showShort(mTokenHelper.isAuth());
            return "";
        }
    }

    //获取机顶盒卡号
    @JavascriptInterface
    public String getCaNum() {
        if (mTokenHelper.isAuth().equals("0000")) {
            return mTokenHelper.getCaidFromNetAndDisk();
        } else {
            ToastUtils.showShort(mTokenHelper.isAuth());
            return "";
        }
    }

    //获取同洲channelId
    @JavascriptInterface
    public String getChannelId(){
        String liveJson = SPUtils.getInstance(Constant.SP_NAME).getString(Constant.SP_LIVE_JSON);
        if (TextUtils.isEmpty(liveJson)) {
            Log.e(TAG, "review: live json null");
            return "";
        }
        FromLiveBean liveBean = mGson.fromJson(liveJson, FromLiveBean.class);
        return liveBean.getChannelId();

    }

    //获取省网serviceId
    @JavascriptInterface
    public String getServiceId(){
        //TODO 屏蔽被动获取直播信息逻辑，暂时用主动获取
//        String liveJson = SPUtils.getInstance(Constant.SP_NAME).getString(Constant.SP_LIVE_JSON);
//        if (TextUtils.isEmpty(liveJson)) {
//            Log.e(TAG, "review: live json is null");
//            return "";
//        }
//        FromLiveBean liveBean = mGson.fromJson(liveJson, FromLiveBean.class);
//        return String.valueOf(Integer.parseInt(liveBean.getSid()));//去掉原始数据首位的0
        return mDVBServiceManager.getLiveInfo().getSid();
    }

    //获取节目名称
    @JavascriptInterface
    public String getProgname(){
        //TODO 屏蔽被动获取直播信息逻辑，暂时用主动获取
//        String liveJson = SPUtils.getInstance(Constant.SP_NAME).getString(Constant.SP_LIVE_JSON);
//        if (TextUtils.isEmpty(liveJson)) {
//            Log.e(TAG, "review: live json is null");
//            return "";
//        }
//        return mGson.fromJson(liveJson, FromLiveBean.class).getProgname();
        return mDVBServiceManager.getProgName();
    }

    //打开APK
    @JavascriptInterface
    public void openApp(String intentJson) {
        Log.w(TAG, "openApp: " + intentJson);
        String defJson = FileUtil.getFromAssets(Utils.getApp(), Constant.FN_TEMPLATE_INTENT);
        String newJson = JsonUtil.mergeJson(defJson, intentJson);

        OutEventBus.getInstance().startEvent(mGson.fromJson(newJson, IntentEventBean.class));
        finish();
    }

    //添加历史纪录
    @JavascriptInterface
    public boolean addRecord(String recordJson) {
        Log.w(TAG, "addRecord: " + recordJson);
        String defJson = FileUtil.getFromAssets(Utils.getApp(), Constant.FN_TEMPLATE_RECORD);
        String newJson = JsonUtil.mergeJson(defJson, recordJson);
        return mRecordDBUtil.insert(mGson.fromJson(newJson, RecordBean.class));
    }

    //获取历史记录列表
    @JavascriptInterface
    public String getRecordList() {
        Log.w(TAG, "getRecordList: ");
        return mGson.toJson(mRecordDBUtil.listAll());
    }

    //一键回看 跳转时移
    @JavascriptInterface
    public void review() {
        String liveJson = SPUtils.getInstance(Constant.SP_NAME).getString(Constant.SP_LIVE_JSON);
        if (TextUtils.isEmpty(liveJson)) {
            Log.e(TAG, "review: live json is null");
            ToastUtils.showLong("当前频道不支持回看");
            finish();
            return;
        }
        FromLiveBean liveBean = mGson.fromJson(liveJson, FromLiveBean.class);
        if (liveBean.isShiftFlag()) {
            IntentEventBean outBean = new IntentEventBean.Builder("", "", "", 0)
                    .setClassName(Constant.CLASS_TIME_SHIFT)
                    .setPackageName(Constant.PACKAGE_TIME_SHIFT)
                    .setAction(Intent.ACTION_VIEW)
                    .setIntentFlag(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    .addKeyValue(Constant.TIME_SHIFT_KEY_CHANNELID, liveBean.getChannelId())
                    .addKeyValue(Constant.TIME_SHIFT_KEY_SID, liveBean.getSid())
                    .addKeyValue(Constant.TIME_SHIFT_KEY_PROGNAME, liveBean.getProgname())
                    .addKeyValue(Constant.TIME_SHIFT_KEY_TSID, liveBean.getTsid())
                    .addKeyValue(Constant.TIME_SHIFT_KEY_TIME, liveBean.getStartTime())
                    .build();

            OutEventBus.getInstance().startEvent(outBean);
        } else {
            Log.w(TAG, "review: isShiftFlag is false");
            ToastUtils.showLong("当前频道不支持回看");
        }
        finish();
    }

    //获取系统类型
    @JavascriptInterface
    public String getSystemType() {
        String systemType = SystemPropUtil.getPropertiesString("ro.product.project","null");
        Log.w(TAG, "getSystemType: "+systemType);
        return systemType;
    }

    //退出智能推荐
    @JavascriptInterface
    public void finish() {
        //关闭悬浮窗
        rx.Observable.just("")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mView.finish();
                    }
                });

    }

}